//
//  MainTableViewController.swift
//  serverMonitor
//
//  Created by joke on 15/12/31.
//  Copyright © 2015年 joke. All rights reserved.
//

import UIKit
import CoreData
import Alamofire
import SwiftyJSON

class MainTableViewController: UITableViewController {
    
    
    var monitorName = [MonitorData]()
    var detailList = [MonitorDetail]() //存放详细信息
    var showList = [MonitorShow]() //存放前台显示信息
    var nilDetail = MonitorDetail()
    var nilShow = MonitorShow()
    
    //获取数据库内monitor数量用来显示
    func numberOfMonitor()  {
        print(1)
        //1
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
        let managedContext = appDelegate.managedObjectContext
        
        //2
        let fetchRequest = NSFetchRequest(entityName: "MonitorData")
        
        //        //清空数据
        //        monitorName = try! managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
        //        for monitor:NSManagedObject in monitorName {
        //            managedContext.deleteObject(monitor)
        //        }
        //        try! managedContext.save()
        
        //3
        do {
            monitorName = try (managedContext.executeFetchRequest(fetchRequest) as! [MonitorData])
            
            
        }
        catch{
            print(error)
        }
    }
    
    func alamofireGet(monitor:MonitorData,index:Int) {
        
        let address = monitor.address! as String
        let name = monitor.name! as String
        var detail = MonitorDetail()
        var show = MonitorShow()
//        print(address)
        show.monitorName = name
        Alamofire.request(.GET, "http://\(address)")
                 .responseJSON { (data) -> Void in
                    print("get the data")
                    switch data.result {
                        case .Success(_):
//                            print("Success")
                            if let value = data.result.value {
                                let json = JSON(value)
                                
                                //存入前台信息
                                show.diskPercent = json["disk"]["percent"].floatValue/100
                                show.memoryPercent = json["memory"]["percent"].floatValue/100
                                show.cachePercent = json["memory"]["realPercent"].floatValue/100
                                if json["memory"]["cached"].stringValue.characters.count == 0{
                                    show.cachePercent = 0
                                    detail.memoryRealUsed = ""
                                    detail.memoryRealFree = ""
                                }
                                
                                
                                show.cpuCore = json["cpu"]["core"].stringValue
                                show.load = json["load"].stringValue
                                
                                self.showList[index] = show
                                //存入详细信息
                                detail.upTime = json["upTime"].stringValue
                                detail.systemTime = json["systemTime"].stringValue
                                detail.cpuCore = json["cpu"]["core"].stringValue
                                detail.cpuModel = json["cpu"]["model"].stringValue
                                detail.load = json["load"].stringValue
                                detail.diskDt = json["disk"]["dt"].stringValue
                                detail.diskDf = json["disk"]["df"].stringValue
                                detail.diskDu = json["disk"]["du"].stringValue
                                detail.memoryTotal = json["memory"]["total"].stringValue
                                detail.memoryUsed = json["memory"]["used"].stringValue
                                detail.memoryFree = json["memory"]["free"].stringValue
                                detail.memoryCached = json["memory"]["cached"].stringValue
                                detail.memoryRealUsed = json["memory"]["realUsed"].stringValue
                                detail.memoryRealFree = json["memory"]["realFree"].stringValue
                                
                                self.detailList[index] = detail
                                
                                self.tableView.reloadData()
                        }
                        
                        case .Failure(let error):
                            print("get the data failure\(error)",error.userInfo)
                    }
        }

    }

    func refresh() {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
            //numberOfMonitor()
            print("refresh")
            //self.tableView.reloadData()
            self.refreshControl?.attributedTitle = NSAttributedString(string: "刷新数据")
            self.detailList = []
            self.showList = []
            //self.tableView(self.tableView, numberOfRowsInSection: self.monitorName.count)
            let nilDetailList = [MonitorDetail](count:self.monitorName.count,repeatedValue:self.nilDetail)
            let nilShowList = [MonitorShow](count: self.monitorName.count, repeatedValue: self.nilShow)
            
            self.detailList = nilDetailList
            self.showList = nilShowList
            //异步刷新数据
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                for (index,monitor) in self.monitorName.enumerate() {
                    self.alamofireGet(monitor, index: index)
                }
                self.refreshControl?.endRefreshing()
            })


        }
        
//        //numberOfMonitor()
//        print("refresh")
//        //self.tableView.reloadData()
//        
//        detailList = []
//        showList = []
//        //self.tableView(self.tableView, numberOfRowsInSection: self.monitorName.count)
//        let nilDetailList = [MonitorDetail](count:monitorName.count,repeatedValue:nilDetail)
//        let nilShowList = [MonitorShow](count: monitorName.count, repeatedValue: nilShow)
//        
//        detailList = nilDetailList
//        showList = nilShowList
//        for (index,monitor) in monitorName.enumerate() {
//            alamofireGet(monitor, index: index)
//        }
//        self.refreshControl?.endRefreshing()
    }

    

    override func viewDidLoad() {
        super.viewDidLoad()
        print("viewDIDLOAD")
        numberOfMonitor()
        
        //下拉刷新
        self.refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
        //refreshControl?.attributedTitle = NSAttributedString(string: "刷新数据")
        
        //tableView.addSubview(refreshControl!)  //此句不添加，否则界面一直有圈圈转
        //注册自定义的xib cell
        tableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "dataCell")
        

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        
        print("row",self.monitorName.count)
        return self.monitorName.count
    }
    
    override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
        return  1
    }

    

    let colorGreen:UIColor = UIColor(red: 92.0/255, green: 184.0/255, blue: 92.0/255, alpha: 1)
    let colorYellow:UIColor = UIColor(red: 240.0/255, green: 173.0/255, blue: 78.0/255, alpha: 1)
    let colorRed:UIColor = UIColor(red: 217.0/255, green: 83.0/255, blue: 79.0/255, alpha: 1)
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        print("create the cell")
        print("\(indexPath.row)",indexPath)
        let cell = tableView.dequeueReusableCellWithIdentifier("dataCell", forIndexPath: indexPath) as! MyTableViewCell
            //alamofireGet(self.monitorName[indexPath.row],index:indexPath)
        
            cell.monitorName.text = showList[indexPath.row].monitorName
            cell.cpuCore.text = showList[indexPath.row].cpuCore
            cell.load.text = showList[indexPath.row].load
            cell.diskPercent.progress = showList[indexPath.row].diskPercent
            cell.memoryPercent.progress = showList[indexPath.row].memoryPercent
            cell.cachePercent.progress = showList[indexPath.row].cachePercent
            
            let diskProgress = cell.diskPercent.progress
            if diskProgress<0.5  {
                cell.diskPercent.progressTintColor = self.colorGreen
            } else if diskProgress<0.75 {
                cell.diskPercent.progressTintColor = self.colorYellow
            } else {
                cell.diskPercent.progressTintColor = self.colorRed
            }

            let memoryProgress = cell.memoryPercent.progress
            if memoryProgress<0.5  {
                cell.memoryPercent.progressTintColor = self.colorGreen
            } else if memoryProgress<0.75 {
                cell.memoryPercent.progressTintColor = self.colorYellow
            } else {
                cell.memoryPercent.progressTintColor = self.colorRed
            }
        

            let cacheProgress = cell.cachePercent.progress
            if cacheProgress == 0 {
                cell.cachePercent.progressTintColor = UIColor.whiteColor()
            }else if cacheProgress<0.5  {
                cell.cachePercent.progressTintColor = self.colorGreen
            } else if memoryProgress<0.75 {
                cell.cachePercent.progressTintColor = self.colorYellow
            } else {
                cell.cachePercent.progressTintColor = self.colorRed
            }
    

        return cell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 150
    }
    
//    let notificationCenter = NSNotificationCenter.defaultCenter()
//    let operationQueue = NSOperationQueue.mainQueue()
//    
//    let applicationWillEnterForegroundObserver =
    
    let notificationCenter = NSNotificationCenter.defaultCenter()
    let operationQueue = NSOperationQueue.mainQueue()
    override func viewWillAppear(animated: Bool) {
        
        
        //加入后台切换到前台后刷新
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh", name: UIApplicationWillEnterForegroundNotification, object: nil)
        
        print("this is a viewWillAppear")
        numberOfMonitor()
        print(self.monitorName.count,"number")
        detailList = []
        showList = []
        //self.tableView(self.tableView, numberOfRowsInSection: self.monitorName.count)
        let nilDetailList = [MonitorDetail](count:monitorName.count,repeatedValue:nilDetail)
        let nilShowList = [MonitorShow](count: monitorName.count, repeatedValue: nilShow)
        
        detailList = nilDetailList
        showList = nilShowList
        for (index,monitor) in monitorName.enumerate() {
            alamofireGet(monitor, index: index)
        }
        
        self.tableView.reloadData()
    }
    
    override func viewWillDisappear(animated: Bool) {
        //转换场景时移除observer
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil)
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let view = DetailViewController(nibName:"DetailViewController",bundle: nil)  //注册自定义xib文件
    
        print(view.nibName)
        view.detail = detailList[indexPath.row]
        self.navigationController?.pushViewController(view, animated: true)
    }
    

    
    // Override to support conditional editing of the table view.
//    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
//        // Return false if you do not want the specified item to be editable.
//        return true
//    }


//    
////     Override to support editing the table view.
//    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
//        if editingStyle == .Delete {
//            // Delete the row from the data source
//            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
//        } else if editingStyle == .Insert {
//            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
//        }    
//    }
//   

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
